import React, { useState, useEffect } from 'react'
import apiService from '../utils/api.js'
import Pagination from './Pagination.jsx'

const SongsManagement = () => {
  // 歌曲管理相关状态
  const [songs, setSongs] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [isAdding, setIsAdding] = useState(false)
  const [isEditing, setIsEditing] = useState(false)
  const [currentSong, setCurrentSong] = useState(null)
  const [formData, setFormData] = useState({
    title: '',
    artist: '',
    album: '',
    coverImageUrl: 'https://via.placeholder.com/300',
    audioUrl: '',
    duration: 0,
    genre: '',
    categoryIds: []
  })
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [songsPerPage] = useState(10) // 每页显示10首歌曲
  const [totalSongs, setTotalSongs] = useState(0)
  
  // 用于文件上传
  const [audioFile, setAudioFile] = useState(null)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [isUploading, setIsUploading] = useState(false)
  
  // 分类列表（用于显示歌曲分类）
  const [categories, setCategories] = useState([])
  // 歌手列表（用于下拉选择）
  const [artists, setArtists] = useState([])
  // 专辑列表（根据选择的歌手动态更新）
  const [albums, setAlbums] = useState([])

  // 获取所有歌曲列表（支持分页）
  const fetchSongs = async (page = 1) => {
    try {
      setLoading(true)
      // 发送带分页参数的请求
      const response = await apiService.get('/songs/paginated', { page, limit: songsPerPage })
      if (response.code === 200) {
        console.log('=== 从API获取的歌曲列表:', response.data);
        
        // 假设API返回的数据结构包含分页信息
        if (response.data && Array.isArray(response.data)) {
          // 如果API返回的是简单数组，我们自己计算分页
          setSongs(response.data)
          setTotalSongs(response.data.length)
          setTotalPages(Math.ceil(response.data.length / songsPerPage))
          setCurrentPage(1) // 重置到第一页
        } else if (response.data && response.data.data) {
          // 如果API返回的是包含分页信息的对象
          setSongs(response.data.data)
          setTotalSongs(response.data.meta.total || 0)
          setTotalPages(response.data.meta.totalPages || 1)
          setCurrentPage(page)
        }
      } else {
        // 如果API调不通，使用模拟数据
        // 创建更多模拟数据用于测试分页
        const mockSongs = Array.from({ length: 25 }, (_, index) => ({
          id: index + 1,
          title: `歌曲${index + 1}`,
          artist: `歌手${Math.floor(index / 5) + 1}`,
          album: `专辑${Math.floor(index / 10) + 1}`,
          cover: `https://via.placeholder.com/300?text=Song${index + 1}`,
          audio: '',
          categoryIds: [(index % 3) + 1],
          categories: [{ id: (index % 3) + 1, name: ['流行', '摇滚', '民谣'][(index % 3)] }]
        }))
        
        // 模拟分页
        const startIndex = (page - 1) * songsPerPage
        const endIndex = startIndex + songsPerPage
        const paginatedSongs = mockSongs.slice(startIndex, endIndex)
        
        setSongs(paginatedSongs)
        setTotalSongs(mockSongs.length)
        setTotalPages(Math.ceil(mockSongs.length / songsPerPage))
        setCurrentPage(page)
      }
    } catch (err) {
      console.error('获取歌曲列表失败:', err)
      setError('获取歌曲列表失败，请重试')
      // 使用模拟数据
      const mockSongs = Array.from({ length: 25 }, (_, index) => ({
        id: index + 1,
        title: `歌曲${index + 1}`,
        artist: `歌手${Math.floor(index / 5) + 1}`,
        album: `专辑${Math.floor(index / 10) + 1}`,
        cover: `https://via.placeholder.com/300?text=Song${index + 1}`,
        audio: '',
        categoryIds: [(index % 3) + 1],
        categories: [{ id: (index % 3) + 1, name: ['流行', '摇滚', '民谣'][(index % 3)] }]
      }))
      
      // 模拟分页
      const startIndex = (page - 1) * songsPerPage
      const endIndex = startIndex + songsPerPage
      const paginatedSongs = mockSongs.slice(startIndex, endIndex)
      
      setSongs(paginatedSongs)
      setTotalSongs(mockSongs.length)
      setTotalPages(Math.ceil(mockSongs.length / songsPerPage))
      setCurrentPage(page)
    } finally {
      setLoading(false)
    }
  }

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await apiService.getCategories()
      if (response.code === 200 && response.data) {
        setCategories(response.data)
      } else {
        // 如果API调不通，使用模拟分类数据
        setCategories([
          { id: 1, name: '流行', description: '流行音乐' },
          { id: 2, name: '摇滚', description: '摇滚音乐' },
          { id: 3, name: '古典', description: '古典音乐' }
        ])
      }
    } catch (error) {
      console.error('获取分类列表失败:', error)
      // 使用模拟分类数据
      setCategories([
        { id: 1, name: '流行', description: '流行音乐' },
        { id: 2, name: '摇滚', description: '摇滚音乐' },
        { id: 3, name: '古典', description: '古典音乐' }
      ])
    }
  }

  // 获取歌手列表
  const fetchArtists = async () => {
    try {
      const response = await apiService.getArtists({ page: 1, limit: 100 })
      if (response.code === 200 && response.data) {
        // 如果API返回的是分页结构，提取data字段
        const artistsData = Array.isArray(response.data) ? response.data : (response.data.data || [])
        setArtists(artistsData)
      } else {
        // 如果API调不通，使用模拟歌手数据
        setArtists([
        ])
      }
    } catch (error) {
      console.error('获取歌手列表失败:', error)
      // 使用模拟歌手数据
      setArtists([
        { id: 1, name: '周杰伦' },
        { id: 2, name: '林俊杰' },
        { id: 3, name: '陈奕迅' },
        { id: 4, name: '张学友' },
        { id: 5, name: '王菲' }
      ])
    }
  }

  // 根据歌手ID获取专辑列表
  const fetchAlbumsByArtist = async (artistId) => {
    if (!artistId) {
      setAlbums([])
      return
    }
    
    try {
      // 使用新的API方法直接获取歌手的所有专辑
      const albumsData = await apiService.getAlbumsBySinger(Number(artistId))
      if (Array.isArray(albumsData) && albumsData.length > 0) {
        setAlbums(albumsData)
      } else {
        // 如果没有获取到专辑数据，使用模拟专辑数据
        setAlbums(getMockAlbumsByArtist(artistId))
      }
    } catch (error) {
      console.error('获取专辑列表失败:', error)
      // 使用模拟专辑数据
      setAlbums(getMockAlbumsByArtist(artistId))
    }
  }

  // 根据歌手ID生成模拟专辑数据
  const getMockAlbumsByArtist = (artistId) => {
    const artist = artists.find(a => a.id === Number(artistId))
    const artistName = artist ? artist.name : '歌手'
    
    return [
      { id: `${artistId}-1`, title: `${artistName}精选集` },
      { id: `${artistId}-2`, title: `${artistName}最新专辑` },
      { id: `${artistId}-3`, title: `${artistName}经典作品集` }
    ]
  }

  // 组件首次加载时获取数据
  useEffect(() => {
    fetchCategories()
    fetchArtists()
    fetchSongs(1) // 默认获取第一页
  }, [])
  
  // 处理分页切换
  const handlePageChange = (page) => {
    if (page >= 1 && page <= totalPages) {
      fetchSongs(page)
    }
  }

  // 处理文件选择
  const handleFileChange = (e) => {
    const file = e.target.files[0]
    if (file) {
      setAudioFile(file)
      // 计算音频文件的时长
      const audio = new Audio(URL.createObjectURL(file))
      audio.onloadedmetadata = () => {
        setFormData(prev => ({ ...prev, duration: Math.floor(audio.duration), title: file.name.split('.')[0] }))
        URL.revokeObjectURL(audio.src) // 释放URL对象
      }
    }
  }

  // 清除选择的文件
  const clearSelectedFile = () => {
    setAudioFile(null)
    const fileInput = document.getElementById('audioFile')
    if (fileInput) {
      fileInput.value = ''
    }
  }

  // 打开添加歌曲表单
  const handleAddSong = () => {
    setIsAdding(true)
    setFormData({
      title: '',
      artist: '',
      album: '',
      coverImageUrl: 'https://via.placeholder.com/300',
      audioUrl: '',
      duration: 0,
      genre: '',
      categoryIds: []
    })
    // 清空专辑列表
    setAlbums([])
    // 确保分类列表已加载
    if (categories.length === 0) {
      fetchCategories()
    }
    // 确保歌手列表已加载
    if (artists.length === 0) {
      fetchArtists()
    }
  }

  // 打开编辑歌曲表单
  const handleEditSong = (song) => {
    setIsEditing(true)
    setCurrentSong(song)
    
    // 提取歌手ID和专辑信息
    const artistId = song.artist && song.artist.id ? song.artist.id : (typeof song.artist === 'string' ? song.artist : '')
    const albumId = song.album && song.album.id ? song.album.id : (typeof song.album === 'string' ? song.album : '')
    
    setFormData({
      title: song.title,
      artist: artistId,
      album: albumId,
      coverImageUrl: song.coverImageUrl,
      audioUrl: song.audioUrl,
      duration: song.duration,
      genre: song.genre,
      categoryIds: Array.isArray(song.categoryIds) ? song.categoryIds : (song.categoryId ? [song.categoryId] : [])
    })
    
    // 确保分类列表已加载
    if (categories.length === 0) {
      fetchCategories()
    }
    
    // 确保歌手列表已加载
    if (artists.length === 0) {
      // 先获取歌手列表，然后再根据选中的歌手获取专辑
      fetchArtists().then(() => {
        if (artistId) {
          fetchAlbumsByArtist(artistId)
        }
      })
    } else if (artistId) {
      // 如果歌手列表已加载，直接根据选中的歌手获取专辑
      fetchAlbumsByArtist(artistId)
    }
  }

  // 提交表单（添加或编辑歌曲）
  const handleSubmit = async (e) => {
    e.preventDefault()
    try {
      // 重置错误信息
      setError('')
      const { artist, album, ...val } = formData
      // 表单数据
      let finalFormData = { ...val, artistId: artist ? Number(artist) : undefined, albumId: album ? Number(album) : undefined }
      
      // 如果有选择音频文件，先上传文件
      if (audioFile) {
        setIsUploading(true)
        setUploadProgress(0)
        
        // 准备元数据
        const metadata = {}
        
        // 上传音频文件
        const uploadResponse = await apiService.uploadAudio(
          audioFile,
          metadata,
          (progress) => setUploadProgress(progress)
        )
        
        if (uploadResponse.code === 200 && uploadResponse.data) {
          // 更新表单数据中的音频URL
          finalFormData.audioUrl = uploadResponse.data.audioUrl
          
          // 重置上传状态
          setIsUploading(false)
          setUploadProgress(0)
          setAudioFile(null)
          clearSelectedFile()
          
          console.log('音频文件上传成功，URL:', finalFormData.audioUrl)
        } else {
          throw new Error('音频文件上传失败')
        }
      }
      
      // 添加或编辑歌曲
      if (isAdding) {
        // 添加新歌
        const response = await apiService.post('/songs', finalFormData)
        if (response.code === 200) {
          fetchSongs() // 重新获取歌曲列表
          setIsAdding(false)
        }
      } else if (isEditing && currentSong) {
        // 编辑现有歌曲
        const response = await apiService.put(`/songs/${currentSong.id}`, finalFormData)
        if (response.code === 200) {
          fetchSongs() // 重新获取歌曲列表
          setIsEditing(false)
          setCurrentSong(null)
        }
      }
    } catch (err) {
      console.error('保存歌曲失败:', err)
      setError('保存歌曲失败，请重试')
      setIsUploading(false)
      setUploadProgress(0)
    }
  }

  // 删除歌曲
  const handleDeleteSong = async (songId) => {
    if (window.confirm('确定要删除这首歌吗？')) {
      try {
        const response = await apiService.delete(`/songs/${songId}`)
        if (response.code === 200) {
          fetchSongs() // 重新获取歌曲列表
        }
      } catch (err) {
        console.error('删除歌曲失败:', err)
        setError('删除歌曲失败，请重试')
      }
    }
  }

  // 关闭表单
  const handleCancel = () => {
    setIsAdding(false)
    setIsEditing(false)
    setCurrentSong(null)
    setError('')
    // 清空专辑列表
    setAlbums([])
  }

  // 处理输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData(prev => ({ ...prev, [name]: value }))
  }

  // 处理歌手选择变化
  const handleArtistChange = (e) => {
    const artistId = e.target.value
    setFormData(prev => ({ ...prev, artist: artistId, album: '' })) // 重置专辑选择
    fetchAlbumsByArtist(artistId)
  }

  // 处理分类选择变化
  const handleCategoryChange = (e) => {
    const selectedOptions = Array.from(e.target.selectedOptions, option => parseInt(option.value))
    setFormData(prev => ({ ...prev, categoryIds: selectedOptions }))
  }

  return (
    <>
      <div className="section-header">
        <button className="btn-add" onClick={handleAddSong}>
          添加歌曲
        </button>
      </div>

      {error && (
        <div className="error-message">
          {error}
          <button onClick={() => setError('')}>×</button>
        </div>
      )}

      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <div className="songs-table-container">
          <table className="songs-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>封面</th>
                <th>歌曲名称</th>
                <th>歌手</th>
                <th>专辑</th>
                <th>分类</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {songs.map((song) => {
                // 优先使用song对象中的categories字段获取分类名称
                // 如果有categories字段，直接使用其中的name属性
                let categoryNames = '';
                if (Array.isArray(song.categories) && song.categories.length > 0) {
                  categoryNames = song.categories.map(cat => cat.name).join(', ');
                } else {
                  // 如果没有categories字段，使用原有的categoryIds或categoryId字段
                  const songCategories = [];
                  if (Array.isArray(song.categoryIds)) {
                    songCategories.push(...song.categoryIds);
                  } else if (song.categoryId) {
                    songCategories.push(song.categoryId);
                  }
                  
                  categoryNames = songCategories
                    .map(catId => {
                      const category = categories.find(cat => cat.id === catId);
                      return category ? category.name : '';
                    })
                    .filter(name => name !== '')
                    .join(', ');
                }
                return (
                <tr key={song.id}>
                  <td>{song.id}</td>
                  <td>
                    <img 
                      src={song.coverImageUrl} 
                      alt={song.title} 
                      className="song-cover-small"
                    />
                  </td>
                  <td>{song.title}</td>
                  <td>{song.artist ? song.artist.name : '-'}</td>
                  <td>{song.album ? song.album.title : '-'}</td>
                  <td>{categoryNames || '-'}</td>
                  <td>
                    <button 
                      className="btn-edit" 
                      onClick={() => handleEditSong(song)}
                    >
                      编辑
                    </button>
                    <button 
                      className="btn-delete" 
                      onClick={() => handleDeleteSong(song.id)}
                    >
                      删除
                    </button>
                  </td>
                </tr>
              )
              })}
            </tbody>
          </table>
          
          {/* 分页控件 */}
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            totalItems={totalSongs}
            itemsPerPage={songsPerPage}
            onPageChange={handlePageChange}
          />
        </div>
      )}

      {/* 歌曲表单 */}
      {(isAdding || isEditing) && (
        <div className="song-form-modal">
          <div className="song-form">
            <h3>{isAdding ? '添加歌曲' : '编辑歌曲'}</h3>
            <form onSubmit={handleSubmit}>
              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="title">歌曲名称</label>
                  <input
                    type="text"
                    id="title"
                    name="title"
                    value={formData.title}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="form-group">
                  <label htmlFor="artist">歌手</label>
                  <select
                    id="artist"
                    name="artist"
                    value={formData.artist}
                    onChange={handleArtistChange}
                    required
                  >
                    <option value="">请选择歌手</option>
                    {artists.map(artist => (
                      <option key={artist.id} value={artist.id}>
                        {artist.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="form-group">
                  <label htmlFor="album">专辑</label>
                  <select
                    id="album"
                    name="album"
                    value={formData.album}
                    onChange={handleInputChange}
                  >
                    <option value="">请选择专辑</option>
                    {albums.map(album => (
                      <option key={album.id} value={album.id || album.title}>
                        {album.title}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              
              <div className="form-row">
                <div className="form-group">
                  <label htmlFor="coverImageUrl">封面URL</label>
                  <input
                    type="text"
                    id="coverImageUrl"
                    name="coverImageUrl"
                    value={formData.coverImageUrl}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="form-group">
                  <label htmlFor="genre">流派</label>
                  <input
                    type="text"
                    id="genre"
                    name="genre"
                    value={formData.genre}
                    onChange={handleInputChange}
                  />
                </div>
                <div className="form-group">
                  <label htmlFor="duration">时长 (秒)</label>
                  <input
                    type="number"
                    id="duration"
                    name="duration"
                    value={formData.duration}
                    onChange={handleInputChange}
                    min="0"
                  />
                </div>
              </div>
              
              <div className="form-group">
                <label htmlFor="categoryIds">分类</label>
                <select
                  id="categoryIds"
                  name="categoryIds"
                  multiple
                  value={formData.categoryIds}
                  onChange={handleCategoryChange}
                >
                  {categories.map(category => (
                    <option key={category.id} value={category.id}>
                      {category.name}
                    </option>
                  ))}
                </select>
                <small>按住Ctrl键可选择多个分类</small>
              </div>
              
              <div className="form-group">
                <label htmlFor="audioFile">上传音频文件</label>
                <input
                  type="file"
                  id="audioFile"
                  accept=".mp3,.wav,.ogg"
                  onChange={handleFileChange}
                />
                {audioFile && (
                  <div className="file-info">
                    <span>{audioFile.name}</span>
                    <button type="button" onClick={clearSelectedFile} className="remove-file">
                      移除
                    </button>
                  </div>
                )}
              </div>
              
              {isUploading && (
                <div className="upload-progress">
                  <div className="progress-bar">
                    <div 
                      className="progress-fill" 
                      style={{ width: `${uploadProgress}%` }}
                    ></div>
                  </div>
                  <span>{uploadProgress}%</span>
                </div>
              )}
              
              <div className="form-actions">
                <button type="button" onClick={handleCancel}>取消</button>
                <button type="submit" disabled={isUploading}>
                  {isUploading ? '上传中...' : '保存'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  )
}

export default SongsManagement